/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.web.panel.code;

import hu.glassy.core.model.Code;
import hu.glassy.web.component.code.CodeSelect;
import hu.glassy.web.panel.common.CustomPanel;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.model.PropertyModel;

/**
 *
 * @author Alexander Molnár <molnar.alexander@sonrisa.hu>
 */
public abstract class CodeSelectPanel extends CustomPanel<Code>
{

  private Code selectedCode;

  public CodeSelectPanel(String id, Code parentCode)
  {
    super(id);
    setOutputMarkupId(true);

    CodeSelect select = new CodeSelect("codeSelect", parentCode, new PropertyModel<Code>(this, "selectedCode"));

    select.add(new OnChangeAjaxBehavior()
    {
      @Override
      protected void onUpdate(AjaxRequestTarget target)
      {
        Component child;

        if (selectedCode == null)
        {
          child = new EmptyPanel("child");
        }
        else
        {
          child = new CodeSelectPanel("child", selectedCode)
          {

            @Override
            public void onChange(Code newSelection)
            {
              // Parent's event handler
              CodeSelectPanel.this.onChange(newSelection);
            }
          };
        }

        child.setOutputMarkupId(true);
        get("child").replaceWith(child);
        target.add(child);

        CodeSelectPanel.this.onChange(selectedCode);
      }
    });

    select.setOutputMarkupId(true);
    add(select);

    add(new EmptyPanel("child").setOutputMarkupId(true));
  }

  public abstract void onChange(Code selectedCode);

}
